# -*- coding: utf-8 -*-
# created on 2016/12/20

from sympy import Symbol, sympify
from sympy.core.function import UndefinedFunction

from mathsolver.functions.base import BaseFunction, BaseEq, new_latex
from mathsolver.functions.hanshu.zhiyu import HanShuZhiYu
from mathsolver.functions.sympy_utils import get_all_child


class AbstractHanShuZhiYu(BaseFunction):
    """求抽象函数的值域：已知 f(x) 的值域为 D, 求 y = g[f(kx+m)] 的值域
    """

    def solver(self, *args):
        # f(x) 值域为 D, 则 f[h(x)] = f(kx+m) 值域为 D, 其中 h(x) 为一次函数
        dd, eq = args
        expr = sympify(eq.value[1])
        fhx = get_all_child(expr, lambda x: isinstance(x.func, UndefinedFunction))[0]
        self.steps.append(["", "%s 的值域为 %s" % (new_latex(fhx), new_latex(dd))])

        # 已知 f(kx+m) 的值域，求 g[f(kx+m)] 的值域
        t = Symbol('t')
        y = expr.subs(fhx, t)
        self.steps.append(["令 %s = t" % new_latex(fhx), "问题转换为求 g(t) = %s, t ∈ %s 的值域" % (new_latex(y), new_latex(dd))])
        out_step = HanShuZhiYu().solver(BaseEq(['y', y]), dd).output
        zhiyu = out_step[0].value

        self.steps.append(["", "求得 y = %s 的值域为 %s" % (new_latex(expr), new_latex(zhiyu))])
        self.label.add("求抽象函数的值域")
        self.output.extend(out_step)
        return self


if __name__ == '__main__':
    pass
